using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using static MissionRecords;

[Serializable]
public class AchieveRecords
{
	private Dictionary<int, int> achieveRecords = new Dictionary<int, int>();

	private Dictionary<int, bool> achieveTakenReward = new Dictionary<int, bool>();
	private List<IntAndIntKeyValue> achieveRecordsList = new List<IntAndIntKeyValue>();

	private List<IntAndBoolKeyValue> achieveTakenRewardList = new List<IntAndBoolKeyValue>();

	public string ToJson()
	{
		achieveRecordsList.Clear();
		foreach (KeyValuePair<int, int> record in achieveRecords)
		{
			achieveRecordsList.Add(new IntAndIntKeyValue(record.Key, record.Value));
		}
		achieveTakenRewardList.Clear();
		foreach (KeyValuePair<int, bool> v in achieveTakenReward)
		{
			achieveTakenRewardList.Add(new IntAndBoolKeyValue(v.Key, v.Value));
		}
		return JsonUtility.ToJson(this);
	}

	public void JsonToObject(string json)
	{
		AchieveRecords _achieveRecords = JsonUtility.FromJson<AchieveRecords>(json);
		if (_achieveRecords == null) return;
		achieveRecords.Clear();
		foreach (IntAndIntKeyValue v in _achieveRecords.achieveRecordsList)
		{
			achieveRecords.Add(v.Key, v.Value);
		}
		achieveTakenReward.Clear();
		foreach (IntAndBoolKeyValue v in _achieveRecords.achieveTakenRewardList)
		{
			achieveTakenReward.Add(v.Key, v.Value);
		}
	}

	public int this[int id]
	{
		get
		{
			if (achieveRecords.ContainsKey(id))
			{
				return achieveRecords[id];
			}
			return 0;
		}
	}

	public void Mark(string levelName, AchieveType type, int num = 1)
	{
		foreach (KeyValuePair<int, AchieveInfo> item in AchieveConfiguration.achieveDictionary)
		{
			if (item.Value.level.CompareTo(levelName) == 0 && (item.Value.type & type) != 0)
			{
				Add(item.Key, num);
				break;
			}
		}
	}

	private void Add(int id, int num)
	{
		if (!achieveRecords.ContainsKey(id))
		{
			achieveRecords.Add(id, num);
		}
		else
		{
			Dictionary<int, int> dictionary;
			int key;
			(dictionary = achieveRecords)[key = id] = dictionary[key] + num;
		}
		if (achieveRecords[id] > AchieveConfiguration.achieveDictionary[id].goal)
		{
			achieveRecords[id] = AchieveConfiguration.achieveDictionary[id].goal;
		}
		ConstantData.achieveRecords = this;
	}

	public void TakeReward(int id)
	{
		if (achieveTakenReward == null)
		{
			achieveTakenReward = new Dictionary<int, bool>();
		}
		achieveTakenReward[id] = true;
		ConstantData.achieveRecords = this;
	}

	public bool IsTakenReward(int id)
	{
		if (achieveTakenReward != null && achieveTakenReward.ContainsKey(id))
		{
			return achieveTakenReward[id];
		}
		return false;
	}
}
